from application import app, db
from flask import Blueprint, request, make_response, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.DataHelper import getCurrentTime
from common.models.eating_menu import EatingMenu
import json, requests
import urllib.request

eating_page = Blueprint("eating_page", __name__)


@eating_page.route('/showeatingmenu', methods=['GET', 'POST'])
def showEatingMenu():
    req = request.values
    city = req['city'] if "city" in req else ""
    a = EatingMenu.query.with_entities(EatingMenu.time).distinct().all()
    rts = []
    id = 0
    for item in a:
        id = id + 1
        time = str(item)
        time1 = time[2:4]
        b = EatingMenu.query.filter_by(time=time1,city=city).all()
        page = []
        for item2 in b:
            temp = dict(id=item2.id, classone=item2.classone, classtwo=item2.classtwo, name=item2.content)
            page.append(temp)

        temp = dict(id=id,name=time1, pages=page)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@eating_page.route('/eatingadmin', methods=['GET', 'POST'])
def eatingadmin():
    eating = EatingMenu.query.all()

    return ops_render("/admin/eatingadmin.html", {"eating": eating})


@eating_page.route('/adminupdate', methods=['GET', 'POST'])
def adminupdate():
    id = request.form.get('id')
    time = request.form.get('time')
    classone = request.form.get('classone')
    classtwo = request.form.get('classtwo')
    content = request.form.get('content')
    city = request.form.get('city')

    b = EatingMenu.query.filter_by(id=id).first()

    b.city = city
    b.time = time
    b.classone = classone
    b.classtwo = classtwo
    b.content = content

    db.session.commit()

    eating = EatingMenu.query.all()

    return ops_render("/admin/eatingadmin.html", {"eating": eating})


@eating_page.route('/admindelete', methods=['GET', 'POST'])
def admindelete():
    id = request.args.get('id')
    b = EatingMenu.query.filter_by(id=id).first()
    db.session.delete(b)
    db.session.commit()
    eating = EatingMenu.query.all()
    return ops_render("/admin/eatingadmin.html", {"eating": eating})

# @eating_page.route('/adminadd', methods=['GET', 'POST'])
# def adminadd():
#     eating = EatingMenu()
#     classtwo = ['汤类','小吃']
#     for
#     eating.nickname = nickname
#
#     user_info.created_time = user_info.updated_time = getCurrentTime()
#     db.session.add(eating)
#     db.session.commit()
#     return ops_render("/admin/eatingadmin.html", {"eating": eating})